/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.auth.server.service.impl;

import com.iwindplus.auth.domain.enums.AuthModuleEnum;
import com.iwindplus.auth.domain.event.LoginLogEvent;
import com.iwindplus.auth.server.config.property.AuthProperty;
import com.iwindplus.auth.server.handler.CustomAuthenticationSuccessHandler;
import com.iwindplus.auth.server.service.OauthService;
import com.iwindplus.log.domain.dto.LoginLogDTO;
import jakarta.annotation.Resource;
import java.util.Objects;
import org.springframework.context.ApplicationContext;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.stereotype.Service;

/**
 * 认证业务层接口实现类.
 *
 * @author zengdegui 2024/12/4 14:18
 */
@Service
public class OauthServiceImpl implements OauthService {

    @Resource
    private OAuth2AuthorizationService authorizationService;

    @Resource
    private AuthProperty property;

    @Resource
    private ApplicationContext applicationContext;

    @Override
    public void logout(String token) {
        OAuth2Authorization authorization = this.authorizationService.findByToken(token, OAuth2TokenType.ACCESS_TOKEN);
        if (Objects.isNull(authorization)) {
            return;
        }
        OAuth2AccessToken accessToken = authorization.getAccessToken().getToken();
        if (Boolean.TRUE.equals(property.getLog().getEnabled())) {
            LoginLogDTO entity = CustomAuthenticationSuccessHandler.buildLoginLog(accessToken, AuthModuleEnum.LOGOUT.getValue(),
                AuthModuleEnum.LOGOUT.getDesc());
            this.applicationContext.publishEvent(new LoginLogEvent(this, entity));
        }
        this.authorizationService.remove(authorization);
    }
}
